//: net/mindview/util/ProcessFiles.java
package net.mindview.util;

import java.io.*;
import java.util.regex.Pattern;

public class E05_ProcessFiles2 {
	public interface Strategy {
		void process(File file);
	}

	private Strategy strategy;
	private String regex;

	public E05_ProcessFiles2(Strategy strategy, String regex) {
		this.strategy = strategy;
		this.regex = regex;
	}

	public void start(String[] args) {
		try {
			if (args.length == 0) {
				processDirectoryTree(new File("."));
			} else
				for (String arg : args) {
					System.err.println(arg);
					File fileArg = new File(arg);
					if (fileArg.isDirectory())
						processDirectoryTree(fileArg);
					else {
						// Allow user to leave off extension:
						Pattern pattern = Pattern.compile(regex);
						if (pattern.matcher(arg).matches()) {
							strategy.process(new File(arg).getCanonicalFile());
						}
					}
				}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void processDirectoryTree(File root) throws IOException {
		for (File file : Directory.walk(root.getAbsolutePath()))
			strategy.process(file.getCanonicalFile());
	}

	// Demonstration of how to use it:
	public static void main(String[] args) {
		new E05_ProcessFiles2(new E05_ProcessFiles2.Strategy() {
			public void process(File file) {
				System.out.println(file);
			}
		}, ".*E.*\\.java").start(args);
	}
} /* (Execute to see output) */// :~
